package com.seek.inter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.service.LoanService;
import com.seek.service.ReadService;
import com.seek.util.CommonUtil;
import com.seek.util.Push2SingleUtil;

/**
 * 货款订单审核相关接口
 *
 */
public class LoanAuditInter {
	
	private LoanService loanService = (LoanService)SpringContextHolder.getBean("loanService");
	private ReadService readService = (ReadService)SpringContextHolder.getBean("readService");
	private Push2SingleUtil push2SingleUtil = (Push2SingleUtil)SpringContextHolder.getBean("push2SingleUtil");
	
	/**
	 * 获取货款待审核列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLoanAuditList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		Long auditorId = reqJson.getLong("auditorId");
		Integer auditDelayMiniut = reqJson.getInteger("auditDelayMiniut");		
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.req_date > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.req_date < ?");
			params.add(rqz);
		}
		if (auditorId != null && auditorId > 0){
			where.append(" and a.auditor_id= ?");
			params.add(auditorId);
		}else{
			where.append(" and a.auditor_id is null");
		}
		if (auditDelayMiniut != null && auditDelayMiniut > 0){
			where.append(" and TIMESTAMPDIFF(MINUTE, now(), a.req_date)> ?");
			params.add(auditDelayMiniut);
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.loan_status=0"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName, a.req_money reqMoney,a.start_time startTime,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName, a.req_money reqMoney,a.start_time startTime,");
		sb.append(" a.end_time endTime, a.req_date reqTime, a.auditor_id auditorId, b.id custId,")
		.append(" (select u.user_name from t_sys_user u where a.auditor_id=u.id) auditName")
		.append(" from t_loan a, t_customer b where a.customer_id=b.id and a.company_id=? and a.loan_status=0");
		sb.append(where).append(" order by a.id asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 货款待审核记录分配给指定用户
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo assignLoanAudit(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String loanIds = reqJson.getString("loanIds");
		Long auditorId = reqJson.getLong("auditorId");	
		
		if(companyId == null || companyId<1 || CommonUtil.isEmpty(loanIds) || auditorId == null || auditorId < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		String sql = "update t_loan set auditor_id=? where company_id=? and loan_status=0 and id in ("+loanIds+")";
		loanService.executeUpdate(sql, new Object[]{auditorId,companyId});
				
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 获取货款待审核列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getUserLoanAuditList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long userId = reqJson.getLong("userId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		Integer auditStatus = reqJson.getInteger("auditStatus");
		if (userId == null || userId < 1 || companyId == null || companyId<1){
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		params.add(userId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.req_date > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.req_date < ?");
			params.add(rqz);
		}
		if (auditStatus != null){
			if (auditStatus <= 1)
				where.append(" and a.loan_status= ?");
			else
				where.append(" and a.loan_status>=?");
			params.add(auditStatus);
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.company_id=? and a.customer_id=b.id and a.auditor_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName, a.req_money reqMoney,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName, a.req_money reqMoney,");
		sb.append(" a.start_time startTime, a.end_time endTime, a.req_date reqTime, a.loan_status loanStatus,")
		.append(" (select count(1) from t_loan b where b.customer_id=a.customer_id) loanNum,")
		.append(" (select sum(case when b.late_fee>0 then 1 else 0 end) from t_loan b where b.customer_id=a.customer_id) overTimeNum,")
		.append(" (select count(1) from t_loan_overdue_log b where b.customer_id=a.customer_id) overdueLogNum,")
		.append(" (select u.user_name from t_sys_user u where a.auditor_id=u.id) auditName,a.audit_time auditTime,b.id custId")
		.append(" from t_loan a, t_customer b where a.company_id=? and a.customer_id=b.id and a.auditor_id=?");
		sb.append(where).append(" order by a.id asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 货款审核
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo loanAudit(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		int auditStatus = CommonUtil.getIntValue(reqJson.getLong("auditStatus"));	
		String auditRemark = reqJson.getString("auditRemark");
		String userId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1 || auditStatus<1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		String sql = "update t_loan set loan_status=?,audit_time=now(),auditor_id=?,audit_remark=? where company_id=? and loan_status=0 and id=?";
		loanService.executeUpdate(sql, new Object[]{auditStatus,userId,auditRemark,companyId,loanId});
		
		// 刷新用户的已使用额度：如果审核失败的话
		if (auditStatus == 1){
			loanService.refreshCachedUsedCredit(loanId);
		}
		
		sql = "select b.client_id from t_loan a, t_customer b where a.customer_id=b.id and a.id=?";
		Map<String,Object> map = readService.findOneMapBySql(sql, new Object[]{loanId});
		if (map != null && map.size() > 0){
			String clientId = map.get("client_id")==null ? null : map.get("client_id").toString();
			if (!CommonUtil.isEmpty(clientId)){
				if (auditStatus == 1)// 审核不通过
					push2SingleUtil.push2Single(Push2SingleUtil.TYPE_OF_LOANAUDIT_FAIL, clientId);
				else if (auditStatus == 2)
					push2SingleUtil.push2Single(Push2SingleUtil.TYPE_OF_LOANAUDIT_SUC, clientId);
			}
		}
		
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 货款审核员申请货款审核任务
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public synchronized ResultInfo reqLoanAudit(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		int num = CommonUtil.getIntValue(reqJson.getLong("num"));	
		String userId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || num < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		String sql = "update t_loan set auditor_id=? where company_id=? and loan_status=0 and auditor_id is null order by id asc limit ?";
		loanService.executeUpdate(sql, new Object[]{userId,companyId,num});
				
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
}
